<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <title th:text="#{share.page.title}">我的分享</title>
    <script th:inline="javascript">
        var _gridWidth;
        var _gridHeight;
        
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;
            _gridHeight = $(document).height()-65 -40;
        }
        
        $(function () {
            resizePageSize();
            var _columnWidth = _gridWidth/5;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/share/queryShareInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'shareUuid',name : 'shareUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{share.file.name}]]*/"文件名",name : 'fileName',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{share.link}]]*/"分享链接",name : 'shareLink',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{share.expire.time}]]*/"有效期",name : 'expireTime',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{share.create.time}]]*/"创建时间",name : 'createTime',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"操作",name : 'shareUuid',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {
                            var html = `<div>`
                            if([[${hasDelPermission}]]) {
                                html += `<a href="#" class="btn" onclick="deleteShare('${v}')" title=[[#{common.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                            }
                            if([[${hasCreatePermission}]]) {
                                html += `<a href="#" class="btn" onclick="shareFile('${v}')" title=[[#{share.create.link}]]><i class="glyphicon glyphicon-share"></i></a>`
                            }
                            html += `</div>`
                            return html;
                        }
                    },
                ],
                resizable : false,
                useRp : true,
                usepager : true,
                autoload : false,
                hideOnSubmit : true,
                showcheckbox : true,
                rowbinddata : true
            });
            
            $("#flexigrid-id").flexReload();

            // 分享对话框
            $("#share-dialog-id").dialog({
                autoOpen: false,
                width: 350,
                modal: true,
                resizable: false,
                title: /*[[#{share.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.close}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
        });

        function query() {
            var fileName = $("#file-name-id").val();
            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"fileName",value:fileName}
                ]
            }).flexReload();
        }

        function shareFile(fileUuid) {
            // 清空之前的内容
            $("#share-link-container").html('');
            // 显示对话框
            $("#share-dialog-id").dialog('open');
            // 显示加载状态
            const loadingText = /*[[#{share.loading}]]*/'';
            $("#share-link-container").html(`<div id="share-loading">${loadingText}</div>`);

            // 获取当前登录用户ID
            const userId = $("#currentUserId").val();

            // 调用后端接口生成分享链接
            fetch(/*[[@{/share/create}]]*/'', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: new URLSearchParams({
                    fileId: fileUuid,
                    userId: userId,
                    expireMinutes: 1440 // 24小时有效期
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(data => {
                $("#share-loading").remove();
                if (data.success) {
                    // 显示分享链接和复制按钮
                    $("#share-link-container").html(`
                        <input type="text" id="share-link-${fileUuid}" value="${data.shareUrl}" readonly class="form-control" style="margin-bottom:10px;">
                        <button class="btn btn-primary" onclick="copyShareLink('share-link-${fileUuid}')">
                            <i class="glyphicon glyphicon-copy"></i> [[#{common.copy}]]
                        </button>
                    `);
                } else {
                    // 显示错误信息
                    $("#share-link-container").html(`<div class="text-danger">${data.message || /*[[#{share.create.fail}]]*/''}</div>`);
                }
            })
            .catch(error => {
                $("#share-loading").remove();
                console.error('分享失败:', error);
                // 显示重试提示
                $("#share-link-container").html(`<div class="text-danger">${/*[[#{share.create.fail.retry}]]*/''}</div>`);
            });
        }

        function copyShareLink(linkId) {
            const linkElement = document.getElementById(linkId);
            linkElement.select();
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    message(/*[[#{share.copy.success}]]*/'');
                } else {
                    message(/*[[#{share.copy.fail}]]*/'');
                }
            } catch (err) {
                message(/*[[#{share.copy.fail}]]*/'');
            }
        }

        function deleteShare(shareUuid) {
            if(confirm(/*[[#{share.delete.confirm}]]*/'')) {
                $.ajax({
                    type: 'post',
                    url: /*[[@{/share/delete}]]*/'',
                    data: {shareUuid: shareUuid},
                    success: function(data) {
                        message(data.msg);
                        if(data.success) {
                            $("#flexigrid-id").flexReload();
                        }
                    },
                    error: function() {
                        message(/*[[#{common.error}]]*/'');
                    }
                });
            }
        }
    </script>
</head>
<body>
<header>
    <input id="file-name-id" th:placeholder="#{share.file.name.plc}">
    <a href="#" class="btn-info btn" onclick="query()">
        <i class="glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>
    <a sec:authorize="hasRole('ROLE_cldk_data_share_create')" href="#" class="btn-info btn" onclick="shareFile()">
        <i class="glyphicon glyphicon-share"></i>
        <span th:text="#{share.create.link}"></span>
    </a>
    <a sec:authorize="hasRole('ROLE_cldk_data_share_del')" href="#" class="btn-info btn" onclick="deleteShare()">
        <i class="glyphicon glyphicon-trash"></i>
        <span th:text="#{common.delete}"></span>
    </a>
</header>

<table id="flexigrid-id"></table>

<!-- 分享对话框 -->
<div id="share-dialog-id" style="display: none">
    <div class="form-group">
        <span th:text="#{share.link}"></span>
        <div id="share-link-container"></div>
    </div>
</div>

<!-- 当前用户ID隐藏域 -->
<input type="hidden" id="currentUserId" th:value="${#authentication.principal.userId}">
</body>
</html>
